﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_HealthTherapyDetailUpdForm
 * 类型：       控制层
 * 功能说明：   健康管家-治疗信息详细登记页面
 * 作者：       章 昕
 * 创建日期：   2007/09/13
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.App.Input.Dao;
using Shpm.App.Input.Bean;
using log4net;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.App.Commons.Utils;
using Shpm.System;
using Shpm.System.Validator;
using Shpm.System.Web.Control;

public partial class App_Input_HealthTherapyDetailUpdForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_HealthTherapyDetailUpdForm));

    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // 取得当前登录的医生id信息
            SysUserManager manager = new SysUserManager(Context);
            SysUserBean sysUserBean = manager.getSysUserBean();
            MstSysUserBean mstSysUserBean =
                sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
            MstEmployeeBean mstEmpBean =
                sysUserBean == null ? null : sysUserBean.getEmployeeBean();
            string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
            string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
            //string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
            //string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
            //string emplyLev = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;

            ViewState["USER_ID"] = loginId;
            ViewState["DOCTOR_ID"] = emplyId;

            int limit = getJobLevel();
            // 医生所属权限范围
            if (limit < 1)
            {
                btnOk.Enabled = true;
                btnSave.Enabled = true;
            }
            else if (limit >= 1)
            {
                btnSupOpn.Enabled = true;
            }

            // 接收传递参数为分页编号
            if (Context.Items.Contains("ParamPageIndex"))
            {
                ViewState["ParamPageIndex"] = Context.Items["ParamPageIndex"];
            }

            ViewState["CURE_ID"] = Convert.ToString(Context.Items["CURE_ID"]);

            if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["ROW_ID"])))
            {
                ViewState["ROW_ID"] = Convert.ToString(Context.Items["ROW_ID"]);
            }
            else
            {
                // view mode
                ViewState["ROW_ID"] = Convert.ToString(Request.QueryString["ROW_ID"]);
                btnOk.Enabled = false;
                btnSave.Enabled = false;
                btnSupOpn.Enabled = false;
                btnBack.Enabled = false;
                txtAdvice.Enabled = false;
                txtCompleteDate.Enabled = false;
                txtConclu.Enabled = false;
                txtNextDate.Enabled = false;
                txtSupOpn.Enabled = false;
                lstCompleteTime.Enabled = false;
                lstNextTime.Enabled = false;
                ckbAutoCal.Enabled = false;
            }

            // 初始化控件
            initPageControls();

            // get data
            bindSelectData(Convert.ToString(ViewState["ROW_ID"]));
        }

    }

    // before render
    void Page_PreRender(object sender, EventArgs e)
    {

    }

    // auto calc next date
    protected void ckbAutoCal_CheckedChanged(object sender, EventArgs e)
    {
        txtNextDate.Text = string.Empty;
        if (ckbAutoCal.Checked)
        {
            DateTime bookDate = DateUtils.convertToDate(lblBookDate.Text).AddDays(Convert.ToDouble(lblFrequency.Text));
            txtNextDate.Text = DateUtils.convertToString(bookDate);
            if (bookDate.CompareTo(DateUtils.convertToDate(lblEndDate.Text)) > 0)
            { txtNextDate.Text = lblEndDate.Text; }
            lstNextTime.SelectedValue = lblBookTime.Text;
        }
        else
        {
            txtNextDate.Focus();
        }
        txtNextDate.ReadOnly = ckbAutoCal.Checked;
        
    }

    // 确定按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            Button btnClick = (Button)sender;

            ComValidateChecker vd = new ComValidateChecker();
            //vd.Add(new CheckRequired(lblBookDate.Text, new ComMessage("E0094", "预约治疗日期")));
            vd.Add(new CheckRequired(txtCompleteDate.Text, new ComMessage("E0094", "实际完成日期")));
            vd.Add(new CheckRequired(txtNextDate.Text, new ComMessage("E0094", "下次治疗日期")));
            //vd.Add(new CheckRequired(txtConclu.Text, new ComMessage("E0094", "治疗情况")));
            //vd.Add(new CheckRequired(txtAdvice.Text, new ComMessage("E0094", "治疗建议")));

            //vd.Add(new CheckDate(lblBookDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "预约治疗日期")));
            vd.Add(new CheckDate(txtCompleteDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "实际完成日期")));
            vd.Add(new CheckDate(txtNextDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "下次治疗日期")));
            vd.Add(new CheckDateRange(lblBookDate.Text, txtNextDate.Text, "yyyy/MM/dd", new ComMessage("E0330", new string[] { "下次治疗日期", "预约治疗日期" })));
            vd.Add(new CheckDateRange(txtCompleteDate.Text, txtNextDate.Text, "yyyy/MM/dd", new ComMessage("E0329", new string[] { "实际完成日期", "下次治疗日期" })));

            MstMemberDoctorBean beanMMD = new MstMemberDoctorBean();
            beanMMD.MemberNo = lblMemId.Text;
            beanMMD.DoctorId = Convert.ToString(ViewState["DOCTOR_ID"]);
            vd.Add(new CheckDataExists(
                new HealthTherapyDao(), HealthTherapyDao.CHECK_MEMBER_DOCTOR_METHOD, beanMMD, new ComMessage("E0901")));
            HealthTherapyBean beanChk = new HealthTherapyBean();
            beanChk.CureId = Convert.ToInt32(ViewState["CURE_ID"]);
            vd.Add(new CheckDataExists(
                new HealthTherapyDao(), HealthTherapyDao.FIND_BY_MEMBER_CURE_ID_METHOD, beanChk, new ComMessage("E0203", "治疗计划")));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            vd = null;
            vd = new ComValidateChecker();
            HealthTherapyBean beanChk2 = new HealthTherapyBean();
            beanChk2.CureId = Convert.ToInt32(ViewState["CURE_ID"]);
            beanChk2.EndDate = DateUtils.convertToDate(txtNextDate.Text);
            vd.Add(new CheckDataExists(
                new HealthTherapyDao(), HealthTherapyDao.CHECK_END_DATE_METHOD, beanChk2, new ComMessage("E0329", new string[] { "下次治疗日期", "计划结束日期" })));
            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // do update
            HealthTherapyDao dao = new HealthTherapyDao();
            HealthTherapyDetailBean beanHTD = new HealthTherapyDetailBean();
            beanHTD.RowId = Convert.ToInt32(ViewState["ROW_ID"]);
            beanHTD = dao.FindByMemberCureDetailId(beanHTD);
            if (beanHTD == null)
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗信息详细");
                return;
            }
            beanHTD.BespokeDate = DateUtils.convertToDate(lblBookDate.Text);
            beanHTD.BespokeTime = lblBookTime.Text;
            beanHTD.FactDate = DateUtils.convertToDate(txtCompleteDate.Text);
            beanHTD.FactTime = lstCompleteTime.SelectedValue;
            beanHTD.Advice = txtAdvice.Text;
            beanHTD.Conclusion = txtConclu.Text;
            beanHTD.CureFlg = false;
            beanHTD.CancelFlg = false;
            beanHTD.EditCount = beanHTD.EditCount.Value + 1;
            // 下次预约日期日期 
            beanHTD.NextDate = DateUtils.convertToDate(txtNextDate.Text);
            beanHTD.NextTime = lstNextTime.SelectedValue;
            //beanHTD.SuperiorOpinion = txtSupOpn.Text;
            beanHTD.UserId = Convert.ToString(ViewState["USER_ID"]);

            if ("Complete".Equals(btnClick.CommandName))
            {
                dao.UpdateComplete(beanHTD);
                btnOk.Enabled = false;
                btnSave.Enabled = false;
            }
            else
            {
                dao.Update(beanHTD);
            }

            bindSelectData(Convert.ToString(beanHTD.RowId));

            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 上级医生意见
    protected void btnSupOpn_Click(object sender, EventArgs e)
    {
        try
        {
            // check
            SysUserManager manager = new SysUserManager(Context);
            SysUserBean sysUserBean = manager.getSysUserBean();
            MstSysUserBean mstSysUserBean =
                sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
            MstEmployeeBean mstEmpBean =
                sysUserBean == null ? null : sysUserBean.getEmployeeBean();
            string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
            string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
            //string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
            //string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
            //string emplyLev = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;
            if (getJobLevel() < 1)
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
                return;
            }

            ComValidateChecker vd = new ComValidateChecker();
            HealthTherapyBean beanChk = new HealthTherapyBean();
            beanChk.CureId = Convert.ToInt32(ViewState["CURE_ID"]);
            vd.Add(new CheckDataExists(
                new HealthTherapyDao(), HealthTherapyDao.FIND_BY_MEMBER_CURE_ID_METHOD, beanChk, new ComMessage("E0203", "治疗计划")));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            HealthTherapyDao dao = new HealthTherapyDao();
            HealthTherapyDetailBean beanHTD = new HealthTherapyDetailBean();
            beanHTD.RowId = Convert.ToInt32(ViewState["ROW_ID"]);
            beanHTD = dao.FindByMemberCureDetailId(beanHTD);
            if (beanHTD == null)
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗信息详细");
                return;
            }

            // check 上级医生监管期限是否已经过期
            if (ViewState["SUP_DOC_LIMIT"] != null && Convert.ToInt32(ViewState["SUP_DOC_LIMIT"]) > 0)
            {
                beanHTD.SuperiorLimit = Convert.ToInt32(ViewState["SUP_DOC_LIMIT"]);
                IList listLimit = dao.CheckSupDocDate(beanHTD);
                if (listLimit != null && listLimit.Count > 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0008").ToString().Replace("{0}", "治疗信息详细");
                    return;
                }
            }

            beanHTD.SuperiorOpinion = txtSupOpn.Text;
            beanHTD.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
            dao.Update(beanHTD);

            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0001").ToString();
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 返回按钮
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string url = "~/App/Input/HealthTherapyDetailSrhForm.aspx";
        Context.Items["ParamPageIndex"] = ViewState["ParamPageIndex"];
        Context.Items["CURE_ID"] = ViewState["CURE_ID"];
        ControllerUtils.Transfer(Context, url, true);
    }

    // bind data to controls
    private void bindSelectData(string rowId)
    {
        HealthTherapyDao dao = new HealthTherapyDao();
        HealthTherapyDetailBean bean = new HealthTherapyDetailBean();

        if (string.IsNullOrEmpty(Convert.ToString(rowId)))
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗信息详细");
            return;
        }

        bean.RowId = Convert.ToInt32(rowId);
        bean = dao.FindByMemberCureDetail(bean);
        if (bean == null)
        {
            ((Design_MasterPage)this.Master).InfoMessage =
               HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗信息详细");
            return;
        }

        // bind get data
        lblDocId.Text = bean.DoctorId;
        lblMemId.Text = bean.MemberNo;
        lblMemName.Text = bean.MemberName;
        lblMemSex.Text = bean.MemberSex;
        lblMemTel.Text = bean.MemberTel;
        lblRoomId.Text = bean.ApartmentNo;
        lblCureType.Text = bean.CureTypeName;
        lblCureName.Text = bean.CureName;
        lblFrequency.Text = Convert.ToString(bean.Frequency);
        if (bean.BeginDate != null)
            lblBeginDate.Text = DateUtils.convertToString(bean.BeginDate.Value);
        if (bean.EndDate != null)
            lblEndDate.Text = DateUtils.convertToString(bean.EndDate.Value);
        if (bean.BespokeDate != null)
        {
            lblBookDate.Text = DateUtils.convertToString(bean.BespokeDate.Value);
            DateTime dt = bean.BespokeDate.Value.AddDays(Convert.ToDouble(bean.Frequency));
            // 下次预约日期
            txtNextDate.ReadOnly = false;
            txtNextDate.Text = DateUtils.convertToString(dt);
            txtNextDate.ReadOnly = true;
            ckbAutoCal.Checked = true;
            if (dt.CompareTo(bean.EndDate.Value) > 0)
            {
                txtNextDate.Text = lblEndDate.Text;
                //txtNextDate.Visible = false;
                //lstNextTime.Visible = false;
            }
        }
        if (bean.FactDate != null)
        { txtCompleteDate.Text = DateUtils.convertToString(bean.FactDate.Value); }
        lblBookTime.Text = bean.BespokeTime;
        lstCompleteTime.SelectedValue = bean.FactTime;
        lstNextTime.SelectedValue = bean.BespokeTime;

        txtAdvice.Text = bean.Advice;
        txtConclu.Text = bean.Conclusion;
        txtSupOpn.Text = bean.SuperiorOpinion;
        lblEditCount.Text = Convert.ToString(bean.EditCount);
        if (bean.CureFlg != null && bean.CureFlg.Value)
        {
            btnOk.Enabled = false;
            btnSave.Enabled = false;
        }

    }

    // bind common catalog data 
    private void initPageControls()
    {
        HealthTherapyDao dao = new HealthTherapyDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 上级医生监管期限
        log.Fatal("\n ***** get SUPERIOR_DOCTOR.LIMIT catalog *****");
        beanComDict.Catalog = "SUPERIOR_DOCTOR.LIMIT";
        lstCat = dao.FindByCatalog(beanComDict);
        ViewState["SUP_DOC_LIMIT"] = "0";
        if (lstCat != null && lstCat.Count > 0)
        {
            ViewState["SUP_DOC_LIMIT"] = ((CommonDictionaryBean)lstCat[0]).Content;
        }

        // 预约日期        
        lstCompleteTime.Items.Clear();
        lstNextTime.Items.Clear();
        for (int i = 1; i <= 24; i++)
        {
            string strTime;
            string strText;
            string strValue;

            if ((i + 8) < 10)
            {
                strTime = "0" + (i + 8) + ":00";
            }
            else
            {
                strTime = ((i + 8) % 24) + ":00";
            }
            strText = strTime;
            strValue = Convert.ToString((i + 8) % 24);
            ListItem item = new ListItem(strText, strText);
            lstCompleteTime.Items.Add(item);
            lstNextTime.Items.Add(item);
        }
    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }

    // 取得职员权限
    private int getJobLevel()
    {
        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
        PersonEmployeeBean beanEmp = new PersonEmployeeBean();
        HealthTherapyDao dao = new HealthTherapyDao();
        beanEmp.EmployeeId = emplyId;
        beanEmp = dao.GetEmployeeJob(beanEmp);
        if (beanEmp == null || string.IsNullOrEmpty(beanEmp.JobLimit))
        { return 0; }
        return Convert.ToInt32(beanEmp.JobLimit);
    }

}
